#pragma once
#include<iostream>
#include<cstdio> //perror
#include<cstdlib> //exit
#include<string>
#include<sys/types.h> //mkfifo
#include<sys/stat.h> //mkfifo
#include<unistd.h>
#include<fcntl.h>
#include"Common.h"

#define DEFAULT_PATH "."
#define FILE_NAME "common"



class NamedPipe
{
public:
    NamedPipe(const std::string& name = FILE_NAME)
    :_name(name)
    {
        
    }
    void Creat()
    {
        umask(0);
        int ret = mkfifo(_name.c_str(),0666);
        if(ret < 0)
        {
            ERR_EXIT("mkfifo");
        }
        std::cout << "管道文件创建成功!!!\n";
    }
    void OpenForRead()
    {
        int fd = open(_path.c_str(),O_CREAT | O_TRUNC | O_RDONLY);
        if(fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout << "open函数执行完毕,文件:" << _path <<"已经打开\n";
        _fd = fd;
    }
    void OpenForWrite()
    {
        int fd = open(_path.c_str(),O_APPEND|O_WRONLY);
        if(fd < 0)
        {
            ERR_EXIT("open");
        }
        _fd = fd;
    }
    void Awake()
    {
        char ch = 'c';
        write(_fd,&ch,1);
    }
    bool Wait()
    {
        char ch = 'c';
        int num = read(_fd,&ch,1);
        if(num > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    ~NamedPipe()
    {
        unlink(FILE_NAME);
    }
private:
    std::string _name = FILE_NAME;
    std::string _path = FILE_NAME;
    int _fd = -1;
};






